<template>
  <div class="product-detail-page">
    <!-- 导航栏 -->
    <nav ref="navRef" class="nav-tabs">
      <button
        v-for="tab in tabs"
        :key="tab.id"
        :class="['nav-tab', { active: activeTab === tab.id }]"
        @click="scrollToSection(tab.id)"
      >
        {{ tab.name }}
        <!-- 激活状态指示器 -->
        <span v-if="activeTab === tab.id" class="active-indicator"></span>
      </button>
    </nav>

    <!-- 评价区域 -->
    <section
      id="reviews"
      :ref="(el) => setSectionRef('reviews', el)"
      class="review-section"
    >
      <h2 class="section-title">买家评价</h2>
      <div class="review-summary">
        <div class="review-header">
          <div class="review-title">
            买家评价
            <span class="review-count">({{ reviewCount }}+)</span>
          </div>
        </div>

        <div class="tag-cloud">
          <div
            v-for="tag in reviewTags"
            :key="tag.id"
            :class="['tag-item', { active: activeTag === tag.id }]"
            @click="handleTagClick(tag.id)"
          >
            {{ tag.name }} {{ tag.count }}
          </div>
        </div>
      </div>

      <div class="user-review">
        <div class="user-info">
          <div class="avatar">
            <img :src="userReview.avatar" :alt="userReview.username" />
          </div>
          <div class="username">{{ userReview.username }}</div>
        </div>

        <div class="review-content">
          {{ userReview.content }}
        </div>

        <div class="review-images">
          <div
            v-for="(image, index) in userReview.images"
            :key="index"
            class="review-image"
          >
            <img :src="image" :alt="`评价图片${index + 1}`" />
          </div>
        </div>
      </div>
    </section>

    <!-- 商品详情 -->
    <section
      id="details"
      :ref="(el) => setSectionRef('details', el)"
      class="product-details"
    >
      <h2 class="section-title">商品详情</h2>
      <ul class="specs-list">
        <li
          v-for="(spec, index) in specifications"
          :key="index"
          :class="['spec-item', { 'spec-item-full': spec.fullWidth }]"
        >
          <div :class="spec.fullWidth ? 'spec-name-full' : 'spec-name'">
            {{ spec.name }}
          </div>
          <div :class="spec.fullWidth ? 'spec-value-full' : 'spec-value'">
            {{ spec.value }}
          </div>
          <template v-if="!spec.fullWidth">
            <div class="spec-name">{{ spec.name2 }}</div>
            <div class="spec-value">{{ spec.value2 }}</div>
          </template>
        </li>
      </ul>
    </section>

    <!-- 售后保障区域 -->
    <section
      id="after-sales"
      :ref="(el) => setSectionRef('after-sales', el)"
      class="after-sales"
    >
      <h2 class="section-title">售后保障</h2>
      <ul class="warranty-list">
        <li
          v-for="warranty in warrantyList"
          :key="warranty.id"
          class="warranty-item"
        >
          <WarrantyIcon :type="warranty.icon" class="warranty-icon" />
          <span>{{ warranty.name }}</span>
        </li>
      </ul>
    </section>

    <!-- 推荐区域 -->
    <section
      id="recommendations"
      :ref="(el) => setSectionRef('recommendations', el)"
      class="recommendations"
    >
      <h2 class="section-title">推荐商品</h2>
      <div class="product-grid">
        <div
          v-for="product in recommendedProducts"
          :key="product.id"
          class="product-card"
          @click="handleProductClick(product.id)"
        >
          <div class="product-image">
            <span>{{ product.name }}</span>
          </div>
          <div class="product-info">
            <div class="product-name">{{ product.fullName }}</div>
            <div class="product-price">¥{{ product.price }}</div>
          </div>
        </div>
      </div>
    </section>

    <!-- 商品对比区域 -->
    <div class="product-compare">
      <button class="compare-btn" @click="handleCompareClick">
        PK 商品对比 >
      </button>
    </div>

    <!-- 滚动进度指示器 -->
    <div v-if="showScrollProgress" class="scroll-progress">
      <div
        class="scroll-progress-bar"
        :style="{ width: scrollProgress + '%' }"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import WarrantyIcon from './WarrantyIcon.vue'

interface Tab {
  id: string
  name: string
}

interface Specification {
  name: string
  value: string
  name2?: string
  value2?: string
  fullWidth?: boolean
}

interface ReviewTag {
  id: string
  name: string
  count: number
}

interface UserReview {
  username: string
  avatar: string
  content: string
  images: string[]
}

interface Warranty {
  id: string
  name: string
  icon: string
}

interface Product {
  id: string
  name: string
  fullName: string
  price: number
}

// 响应式数据
const activeTab = ref('reviews')
const activeTag = ref('')
const reviewCount = ref(20)
const showScrollProgress = ref(false)
const scrollProgress = ref(0)

// 引用
const navRef = ref<HTMLElement>()
const sectionRefs = reactive<{ [key: string]: HTMLElement | null }>({})

const tabs: Tab[] = [
  { id: 'reviews', name: '买家评论' },
  { id: 'details', name: '商品详情' },
  { id: 'after-sales', name: '售后保障' },
  { id: 'recommendations', name: '商品推荐' },
]

const specifications: Specification[] = [
  { name: '品牌', value: 'Apple', name2: '商品编号', value2: '10027822276' },
  { name: 'CPU型号', value: 'A19', name2: '机身颜色', value2: '薰衣草紫色' },
  { name: '特征特质', value: '无', name2: '屏幕分辨率', value2: 'FHD+' },
  {
    name: '风格',
    value: '商务，科技',
    name2: '屏幕材质',
    value2: 'OLED全面屏',
  },
  {
    name: '后摄主像素',
    value: '4800万像素',
    name2: '三防标准',
    value2: 'IP68',
  },
  { name: '入网型号', value: 'A3521', name2: '上市日期', value2: '2025-09-10' },
  {
    name: '国补备案型号',
    value: 'MG704CH/A',
    name2: '机型',
    value2: 'Apple iPhone 17',
  },
  {
    name: '机身重量',
    value: '177g',
    name2: '机身尺寸',
    value2: '长149.6mm；宽71.5mm；厚7.95mm',
  },
  { name: '机身颜色', value: '薰衣草紫色', name2: '机身内存', value2: '256GB' },
  { name: '存储卡', value: '不支持', name2: '屏幕刷新率', value2: '120Hz' },
  { name: '屏幕尺寸', value: '6.3英寸', name2: '屏幕特色', value2: '无' },
  {
    name: '充电功率',
    value: '40W',
    name2: '无线充电',
    value2: '以官网信息为准',
  },
  { name: '系统', value: 'iOS', name2: '5G网络', value2: '支持5G' },
  { name: 'SIM卡数量', value: '2个', name2: '生物识别', value2: '人脸识别' },
  {
    name: '后摄2-超广角像素',
    value: '4800万像素',
    name2: '后摄3-长焦像素',
    value2: '普通(以官网信息为准)',
  },
  {
    name: '前摄主像素',
    value: '1800万像素',
    name2: '拍照特色',
    value2: '杜比视界',
  },
  {
    name: '包装清单',
    value: '装有iOS 26的iPhone，USB-C充电线（1米）',
    fullWidth: true,
  },
]

const reviewTags: ReviewTag[] = [
  { id: 'comfort', name: '手感很舒服', count: 300 },
  { id: 'camera', name: '拍照效果超清晰', count: 262 },
  { id: 'charging', name: '充电超快速', count: 114 },
  { id: 'smooth', name: '用起来超流畅', count: 250 },
  { id: 'battery', name: '续航超持久', count: 75 },
  { id: 'convenient', name: '使用顺手', count: 38 },
  { id: 'thin', name: '机身超轻薄', count: 44 },
  { id: 'color', name: '颜色超鲜艳', count: 19 },
  { id: 'border', name: '边框超窄', count: 9 },
  { id: 'sound', name: '音质超清晰', count: 19 },
  { id: 'night', name: '夜拍效果惊艳', count: 4 },
  { id: 'screen', name: '屏量超大', count: 11 },
]

const userReview: UserReview = {
  username: '小**',
  avatar:
    'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"%3E%3Ccircle cx="20" cy="20" r="20" fill="%23e0e0e0"/%3E%3Ccircle cx="20" cy="16" r="6" fill="%23999"/%3E%3Cpath d="M20,40 C8,40 0,32 0,20 C0,8 8,0 20,0 C32,0 40,8 40,20 C40,32 32,40 20,40 Z M20,38 C30,38 38,30 38,20 C38,10 30,2 20,2 C10,2 2,10 2,20 C2,30 10,38 20,38 Z" fill="%23999"/%3E%3C/svg%3E',
  content:
    '这款手机真是棒极了！外形时尚，手感挺好。屏幕清晰流畅，操作非常顺手。处理器强大，玩游戏也不会卡顿。摄像头表现也很出色，拍出来的照片特别美。最喜欢它的iOS系统，用起来超级舒服。总之，这是一次非常满意的购物体验，强烈推...',
  images: [
    'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"%3E%3Crect width="80" height="80" fill="%23f0f0f0"/%3E%3Ctext x="50%25" y="50%25" font-size="14" text-anchor="middle" alignment-baseline="middle" fill="%23999"%3E评价图片%3C/text%3E%3C/svg%3E',
    'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"%3E%3Crect width="80" height="80" fill="%23f0f0f0"/%3E%3Ctext x="50%25" y="50%25" font-size="14" text-anchor="middle" alignment-baseline="middle" fill="%23999"%3E评价图片%3C/text%3E%3C/svg%3E',
    'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"%3E%3Crect width="80" height="80" fill="%23f0f0f0"/%3E%3Ctext x="50%25" y="50%25" font-size="14" text-anchor="middle" alignment-baseline="middle" fill="%23999"%3E评价图片%3C/text%3E%3C/svg%3E',
  ],
}

const warrantyList: Warranty[] = [
  { id: 'return', name: '7天无理由退货', icon: 'return' },
  { id: 'exchange', name: '15天质量问题换货', icon: 'exchange' },
  { id: 'warranty', name: '全国联保1年', icon: 'warranty' },
  { id: 'extended', name: '延保服务可选', icon: 'extended' },
]

const recommendedProducts: Product[] = [
  {
    id: '1',
    name: 'iPhone 16 Pro',
    fullName: 'Apple iPhone 16 Pro',
    price: 8999,
  },
  { id: '2', name: 'iPhone 15', fullName: 'Apple iPhone 15', price: 5999 },
  { id: '3', name: 'AirPods Pro', fullName: 'AirPods Pro 2', price: 1899 },
  {
    id: '4',
    name: 'Apple Watch',
    fullName: 'Apple Watch Series 9',
    price: 2999,
  },
]

// 设置区域引用
const setSectionRef = (id: string, el: HTMLElement | null) => {
  if (el) {
    sectionRefs[id] = el
  }
}

// 获取导航栏高度
const getNavHeight = (): number => {
  return navRef.value?.offsetHeight || 60
}

// 精准滚动到目标区域
const scrollToSection = (sectionId: string) => {
  const section = sectionRefs[sectionId]
  if (!section) return

  const navHeight = getNavHeight()
  const sectionRect = section.getBoundingClientRect()
  const sectionTop = sectionRect.top + window.scrollY

  // 计算目标滚动位置：区域顶部 - 导航栏高度 + 1px 确保紧贴
  const targetScrollTop = sectionTop - navHeight + 1

  window.scrollTo({
    top: targetScrollTop,
    behavior: 'smooth',
  })

  // 更新激活状态
  activeTab.value = sectionId

  // 添加点击反馈
  provideClickFeedback(sectionId)
}

// 点击反馈效果
const provideClickFeedback = (sectionId: string) => {
  const section = sectionRefs[sectionId]
  if (section) {
    section.classList.add('section-highlight')
    setTimeout(() => {
      section.classList.remove('section-highlight')
    }, 1000)
  }
}

// 滚动处理
const handleScroll = () => {
  const navHeight = getNavHeight()
  const scrollPosition = window.scrollY + navHeight + 10 // 添加小偏移量提高灵敏度

  // 计算滚动进度
  calculateScrollProgress()

  // 检测当前激活的标签
  let currentActive = 'reviews'
  let minDistance = Infinity

  // 找到距离顶部最近的区域
  tabs.forEach((tab) => {
    const section = sectionRefs[tab.id]
    if (section) {
      const sectionTop = section.offsetTop
      const distance = Math.abs(scrollPosition - sectionTop)

      if (distance < minDistance && scrollPosition >= sectionTop - 50) {
        minDistance = distance
        currentActive = tab.id
      }
    }
  })

  // 只在确实发生变化时更新
  if (activeTab.value !== currentActive) {
    activeTab.value = currentActive
  }
}

// 计算滚动进度
const calculateScrollProgress = () => {
  const scrollHeight =
    document.documentElement.scrollHeight - window.innerHeight
  const scrolled = (window.scrollY / scrollHeight) * 100
  scrollProgress.value = Math.min(100, Math.max(0, scrolled))

  // 在滚动超过10%时显示进度条
  showScrollProgress.value = scrolled > 10
}

// 事件处理函数
const handleTagClick = (tagId: string) => {
  activeTag.value = activeTag.value === tagId ? '' : tagId
}

const handleProductClick = (productId: string) => {
  console.log('点击产品:', productId)
}

const handleCompareClick = () => {
  console.log('点击商品对比')
}

onMounted(async () => {
  await nextTick()
  window.addEventListener('scroll', handleScroll, { passive: true })

  // 初始检测一次
  handleScroll()
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style lang="scss" scoped>
.product-detail-page {
  max-width: 75rem;
  margin: 0 auto;
  padding: 0.625rem 0.75rem;
  background-color: #f5f5f5;
  position: relative;

  .nav-tabs {
    display: flex;
    background-color: #fff;
    border-radius: 0.5rem 0.5rem 0 0;
    box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.05);
    overflow: hidden;
    position: sticky;
    top: 0;
    z-index: 100;

    .nav-tab {
      flex: 1;
      text-align: center;
      padding: 0.9375rem 0;
      font-size: 1rem;
      color: #666;
      cursor: pointer;
      transition: all 0.3s;
      background: none;
      border: none;
      position: relative;

      &:hover {
        color: #ff6700;
        background-color: #fff8f6;
      }

      &.active {
        color: #ff6700;
        font-weight: bold;

        .active-indicator {
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60%;
          height: 0.125rem;
          background-color: #ff6700;
          border-radius: 0.125rem 0.125rem 0 0;
        }
      }
    }
  }

  // 区域高亮效果
  .review-section,
  .product-details,
  .after-sales,
  .recommendations {
    transition: all 0.5s ease;

    &.section-highlight {
      animation: highlight-pulse 1s ease;
    }
  }

  @keyframes highlight-pulse {
    0% {
      box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.05);
    }
    50% {
      box-shadow: 0 0.125rem 1.25rem rgba(255, 103, 0, 0.2);
    }
    100% {
      box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.05);
    }
  }

  // 滚动进度条
  .scroll-progress {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 0.1875rem;
    background-color: rgba(255, 255, 255, 0.1);
    z-index: 1000;
    transition: opacity 0.3s ease;

    .scroll-progress-bar {
      height: 100%;
      background: linear-gradient(90deg, #ff6700, #ff8c00);
      transition: width 0.1s ease;
      border-radius: 0 0.125rem 0.125rem 0;
    }
  }

  // 确保标题紧贴导航栏
  .section-title {
    scroll-margin-top: 5rem;
    padding-top: 0.5rem;
  }

  .product-details,
  .review-section,
  .after-sales,
  .recommendations {
    font-size: 0.75rem;
    background-color: #fff;
    padding: 1.425rem;
    margin-bottom: 1.25rem;
    border-radius: 0 0 0.5rem 0.5rem;
    box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 1rem;
      font-weight: bold;
      margin-bottom: 1.25rem;
      padding-bottom: 0.625rem;
      border-bottom: 0.0625rem solid #f0f0f0;
      color: #333;
      text-align: center;
    }
  }

  .specs-list {
    list-style: none;
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 1.875rem;

    .spec-item {
      width: 100%;
      display: flex;
      border-bottom: 0.0625rem solid #f0f0f0;

      &:nth-child(odd) {
        background-color: #f9f9f9;
      }

      &:nth-child(even) {
        background-color: #fff;
      }

      &.spec-item-full {
        width: 100%;
        background-color: #f9f9f9;
      }

      .spec-name,
      .spec-name-full {
        padding: 0.75rem 0.9375rem;
        font-weight: bold;
        border-right: 0.0625rem solid #f0f0f0;
      }

      .spec-name {
        width: 25%;
      }

      .spec-name-full {
        width: 12.5%;
      }

      .spec-value,
      .spec-value-full {
        padding: 0.75rem 0.9375rem;
      }

      .spec-value {
        width: 25%;
      }

      .spec-value-full {
        width: 87.5%;
      }
    }
  }

  .review-summary {
    margin-bottom: 1.25rem;

    .review-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1.25rem;
      padding-bottom: 0.9375rem;
      border-bottom: 0.0625rem solid #f0f0f0;

      .review-title {
        font-weight: bold;

        .review-count {
          color: #ff6700;
          margin-left: 0.3125rem;
        }
      }
    }

    .tag-cloud {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 0.625rem;
      margin-bottom: 1.25rem;

      .tag-item {
        background-color: #f8f8f8;
        padding: 0.5rem 0.75rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;

        &:hover,
        &.active {
          background-color: #ff6700;
          color: white;
        }
      }
    }
  }

  .user-review {
    background-color: #fff;
    margin-bottom: 1.25rem;
    border-radius: 0.5rem;

    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 0.9375rem;

      .avatar {
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        background-color: #f0f0f0;
        margin-right: 0.625rem;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .username {
        font-weight: bold;
        font-size: 0.875rem;
      }
    }

    .review-content {
      margin-bottom: 0.9375rem;
      line-height: 1.6;
      font-size: 0.75rem;
    }

    .review-images {
      display: flex;
      gap: 0.625rem;
      margin-bottom: 0.9375rem;

      .review-image {
        width: 5rem;
        height: 5rem;
        border-radius: 0.25rem;
        background-color: #f0f0f0;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }

  .warranty-list {
    list-style-type: none;

    .warranty-item {
      padding: 0.625rem 0;
      border-bottom: 0.0625rem solid #f0f0f0;
      display: flex;
      align-items: center;

      &:last-child {
        border-bottom: none;
      }

      .warranty-icon {
        width: 1.5rem;
        height: 1.5rem;
        margin-right: 0.625rem;
        color: #ff6700;
      }
    }
  }

  .product-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1.25rem;

    .product-card {
      border: 0.0625rem solid #f0f0f0;
      border-radius: 0.5rem;
      overflow: hidden;
      transition: all 0.3s;
      cursor: pointer;

      &:hover {
        transform: translateY(-0.3125rem);
        box-shadow: 0 0.3125rem 0.9375rem rgba(0, 0, 0, 0.1);
      }

      .product-image {
        height: 11.25rem;
        background-color: #f8f8f8;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .product-info {
        padding: 0.9375rem;

        .product-name {
          font-weight: bold;
          margin-bottom: 0.3125rem;
        }

        .product-price {
          color: #ff6700;
          font-weight: bold;
        }
      }
    }
  }

  .product-compare {
    background-color: #fff;
    padding: 1.25rem;
    border-radius: 0.5rem;
    box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.05);
    text-align: center;

    .compare-btn {
      display: inline-block;
      padding: 0.625rem 1.25rem;
      background-color: #ff6700;
      color: white;
      border-radius: 0.25rem;
      font-weight: bold;
      cursor: pointer;
      transition: all 0.3s;
      border: none;

      &:hover {
        background-color: #f25807;
      }
    }
  }
}

@media (max-width: 48rem) {
  .product-detail-page {
    .nav-tabs .nav-tab {
      font-size: 0.875rem;
      padding: 0.75rem 0;
    }

    .specs-list {
      .spec-item,
      .spec-item-full {
        width: 100%;
      }

      .spec-name,
      .spec-value,
      .spec-name-full,
      .spec-value-full {
        width: 50%;
        font-size: 0.875rem;
      }
    }

    .review-summary .tag-cloud {
      grid-template-columns: repeat(3, 1fr);
    }

    .product-grid {
      grid-template-columns: repeat(2, 1fr);
    }

    .section-title {
      scroll-margin-top: 4.375rem;
    }
  }
}
</style>
